package org.caiotte.service.impl;


import org.caiotte.domain.Department;
import org.caiotte.mapper.DepartmentMapper;
import org.caiotte.query.DepartmentQuery;
import org.caiotte.service.IDepartmentService;
import org.caiotte.util.PageList;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
@Transactional(readOnly = true,propagation = Propagation.SUPPORTS)
public class DepartmentServiceImpl implements IDepartmentService {

    @Autowired
    private DepartmentMapper departmentMapper;


    @Override
    @Transactional
    public void save(Department department) {
        departmentMapper.save(department);
    }

    @Override
    @Transactional
    public void update(Department department) {
        departmentMapper.update(department);
    }

    @Override
    @Transactional
    public void removeById(Long id) {
        departmentMapper.deleteById(id);
    }

    @Override
    public List<Department> queryAll() {
        return departmentMapper.loadAll();
    }

    @Override
    public Department queryById(Long id) {
        return departmentMapper.loadById(id);
    }

    @Override
    public PageList<Department> queryPage(DepartmentQuery departmentQuery) {
        Long total = departmentMapper.queryCount(departmentQuery);
        List<Department> rows = departmentMapper.queryData(departmentQuery);
        return new PageList<Department>(total,rows);
    }

    @Override
    public void batchRemove(List<Long> ids) {
        departmentMapper.batchRemove(ids);
    }

    @Override
    public List<Department> queryTree(){
        //一次性把所有数据查询出来 放到内存中
        List<Department> departments = departmentMapper.loadAll();
        //为了后面找自己的父亲，我们这里可以把整体的部门数据，转换一份成Map<id,department>
        //简写方式: Map<Long, Department> allDepts = departments.stream().collect(Collectors.toMap(Department::getId, dept -> dept));
        Map<Long , Department> allDepts =  new HashMap<>();
        for (Department department : departments) {
            allDepts.put(department.getId(),department);
        }
        //最高级部门
        ArrayList<Department> firstDept = new ArrayList<>();
        for (Department tmp : departments) {
            if (tmp.getParent_id() == null){
                //在所有数据中找到第一层级的firstDepts  返回最外层数据
                firstDept.add(tmp);
            }else {
                //不是第一层级的话就找自己的上一层级  并且将自己放入上一层级的children中
                Department parent = allDepts.get(tmp.getParent_id());
                if (parent != null){
                    parent.getChildren().add(tmp);
                }
            }
        }
        return firstDept;
    }




}
